package com.middlegroup.payadmin.controller.sys;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.middlegroup.common.annotation.AllLog;
import com.middlegroup.common.exception.BusinessException;
import com.middlegroup.payadmin.controller.BaseController;
import com.middlegroup.payadmin.pojo.dto.DataGrid;
import com.middlegroup.payadmin.pojo.dto.ManagerDto;
import com.middlegroup.payadmin.pojo.dto.SettleCycleDto;
import com.middlegroup.payadmin.pojo.dto.SettleMethod;
import com.middlegroup.payadmin.pojo.message.ApiResult;
import com.middlegroup.payadmin.pojo.po.*;
import com.middlegroup.payadmin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jdk.nashorn.api.scripting.JSObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author pc
 */
@Controller
@RequestMapping("/sys/channels")
@Api(value = "通道管理", description = "通道管理", tags = "1.2")
public class ChannelsController extends BaseController {

    @Resource
    private ChannelsService channelsService;
    @Resource
    private ServiceTypeService serviceTypeService;

    @Resource
    private ChannelBankRouterService channelBankRouterService;



    @ApiIgnore
    @GetMapping("/list")
    public String list() {
        return "sys/channels/list";
    }

    @ApiIgnore
    @GetMapping(value = "/edit")
    public String edit(Long id) {
        if (id != null) {
            Channels channels = this.channelsService.selectById(id);
            if (null == channels){
                throw BusinessException.notFound("该数据已失效");
            }else {
                request.setAttribute("dto",channels);
            }
        }
        request.setAttribute("parServiceTypes", this.serviceTypeService.listParServiceType());
        request.setAttribute("serviceTypes",this.serviceTypeService.listServiceType());
        List<SettleCycleDto> settleCycles = new ArrayList<SettleCycleDto>();
        SettleCycleDto settleCycleDto = new SettleCycleDto();
        settleCycleDto.setName("T0");
        settleCycleDto.setText("T0");
        settleCycles.add(settleCycleDto);
        settleCycleDto =  new SettleCycleDto();
        settleCycleDto.setName("T1");
        settleCycleDto.setText("T1");
        settleCycles.add(settleCycleDto);
        settleCycleDto =  new SettleCycleDto();
        settleCycleDto.setName("D0");
        settleCycleDto.setText("D0");
        settleCycles.add(settleCycleDto);
        settleCycleDto =  new SettleCycleDto();
        settleCycleDto.setName("D1");
        settleCycleDto.setText("D1");
        settleCycles.add(settleCycleDto);
        request.setAttribute("settleCycles",settleCycles);
        List<SettleMethod> settleMethods = new ArrayList<>();
        SettleMethod settleMethod = new SettleMethod();
        settleMethod.setName("1");
        settleMethod.setText("订单每笔");
        settleMethods.add(settleMethod);
        settleMethod = new SettleMethod();
        settleMethod.setName("2");
        settleMethod.setText("金额百分比");
        settleMethods.add(settleMethod);
        request.setAttribute("settleMethods",settleMethods);

        return "sys/channels/edit";
    }

    @ApiOperation(value = "带条件分页查询")
    @GetMapping(value = "/query")
    @ResponseBody
    public PageInfo<Channels> query(DataGrid grid, String name, Long serviceType) {
        return this.channelsService.listChannels(grid, name, serviceType);
    }

    @ApiOperation(value = "添加/修改通道信息")
    @AllLog(module = "通道管理", methods = "保存通道", description = "添加/修改通道信息")
    @PostMapping(value = "/save")
    @ResponseBody
    @Transactional(readOnly = false)
    public ApiResult<Channels> save(Channels dto) {
        EntityWrapper<ServiceType> ew = new EntityWrapper<>();
        ew.where("service_code={0}",dto.getServiceType());
        ServiceType serviceType = serviceTypeService.selectOne(ew);
        if (null != serviceType){
            dto.setServiceParType(serviceType.getPType());
        }
        //通道银行绑定
        if(StringUtils.isNotBlank(dto.getBankCode())){
            String[] bankCodeArr = dto.getBankCode().split(",");
            for (String bankCode :bankCodeArr){
                ChannelBankRouter channelBankRouter = new ChannelBankRouter();
                channelBankRouter.setChannelCode(dto.getCode());
                channelBankRouter.setBankCode(bankCode);
                channelBankRouter.setServiceType(serviceType.getServiceCode());
                channelBankRouterService.saveOrUpdate(channelBankRouter);
            }
        }

        //删除
        if(StringUtils.isNotBlank(dto.getUnselectBankCode())){
            String[] bankCodeArr = dto.getUnselectBankCode().split(",");
            for (String bankCode :bankCodeArr){
               EntityWrapper entityWrapper = new EntityWrapper();
               entityWrapper.where("channel_code={0} and bank_code={1}",dto.getCode(),bankCode);
                channelBankRouterService.delete(entityWrapper);
            }
        }
        if (dto.getId() != null) {
            //不更新类型
            dto.setServiceParType(null);
            dto.setServiceType(null);
            return ApiResult.getResponse(this.channelsService.updateById(dto));
        }

        //判断code是否被用了
        EntityWrapper<Channels> entityWrapper = new EntityWrapper<>();
        entityWrapper.where("code={0}",dto.getCode());
        Channels channels = channelsService.selectOne(entityWrapper);
        if (null != channels){
            ApiResult.getFailure("通道码已经存在,请更换!");
        }
        return ApiResult.getResponse(this.channelsService.insert(dto));
    }

    @ApiOperation(value = "删除通道信息")
    @AllLog(module = "通道管理", methods = "移除通道", description = "删除通道信息")
    @PostMapping(value = "/remove")
    @ResponseBody
    public ApiResult<String> del(Integer[] ids) {
        Lists.newArrayList(ids).forEach(this.channelsService::deleteById);
        return ApiResult.SUCCESS;
    }

    /**
     * 采用网上大神的POI操作, 速度杠杠的：http://git.oschina.net/jueyue/easypoi<br>
     *
     * @param response 响应流
     * @throws Exception 异常信息
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    @ApiOperation(value = "通道导出", hidden = true)
    @RequiresPermissions("sys:channels:export")
    public void export(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        ExportParams params = new ExportParams("通道列表", "通道列表详情", ExcelType.XSSF);
        map.put(NormalExcelConstants.DATA_LIST, this.channelsService.selectList(null));
        map.put(NormalExcelConstants.CLASS, Channels.class);
        map.put(NormalExcelConstants.PARAMS, params);
        map.put(NormalExcelConstants.FILE_NAME, "通道列表");
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }
    @ApiOperation(value = "带条件分页查询")
    @ResponseBody
    @RequestMapping(value = "/getChannelBanks")
    public List<Bank> getChannelBanks(String code) {
        return this.channelsService.getChannelBanks(code);
    }


}
